import { createBrowserHistory } from 'history'
import print from './print';

const history = createBrowserHistory()

export default function request (method, url, body) {
  method = method.toUpperCase();
  if (method === 'GET') {
    // fetch的GET不允许有body，参数只能放在url中
    body = undefined;
  } else {
    body = body && JSON.stringify(body);
  }

  return fetch(url, {
    method,
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
      timeout : 20 * 1000,
    },
    body
  })
    .then((res) => {
      print.log(res,'res');
      if (res.status === 401) {
        print.log(history,'history');
        // history.push('/login');
        return {code:0, message: 'need login'} //Promise.reject("need login");
      } else {
        var session 
        
        if (session) {
          // sessionStorage.setItem('access_token', token);
        }
        return res.json();
      }
    });
}

export const get = url => request('GET', url);
export const post = (url, body) => request('POST', url, body);
export const put = (url, body) => request('PUT', url, body);
export const del = (url, body) => request('DELETE', url, body);